import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_tv/flutter_swiper.dart';
import 'package:flutter_trip/dao/home_dao.dart';
import 'package:flutter_trip/models/common_model.dart';
import 'package:flutter_trip/models/grid_nav_model.dart';
import 'package:flutter_trip/models/home_model.dart';
import 'package:flutter_trip/models/sales_box_model.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/pages/speak_page.dart';
import 'package:flutter_trip/util/navigator_util.dart';
import 'dart:convert';

import 'package:flutter_trip/widget/grid_nav.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/local_nav.dart';
import 'package:flutter_trip/widget/sales_box.dart';
import 'package:flutter_trip/widget/search_bar.dart';
import 'package:flutter_trip/widget/sub_nav.dart';
import 'package:flutter_trip/widget/webview.dart';


const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAR_DEFALUT_TEXT = '网红打卡 景点 酒店 美食';
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _imageUrls =['http://cools.qctt.cn/1638871939873.jpeg?imageMogr2/size-limit/1024k!',
    'http://cools.qctt.cn/1638871816572.jpeg?imageMogr2/size-limit/1024k!',
    'http://cools.qctt.cn/1638877748114.jpeg',
    'http://cools.qctt.cn/FuI7c-LIkfrOIVCvP-bdSdLgV6Dz'
  ];
  double appBarApha  = 0;
  String resultString ="";

  List <CommonModel> bannerList = [];
  List <CommonModel> localNavList = [];
  List <CommonModel> subNavList = [];
  late GridNavModel gridNavModel;
  late SalesBoxModel salesBox;
  bool _loading = true;

  void _onScroll(offset) {
//    print(offset);
    double alpho = offset/APPBAR_SCROLL_OFFSET;
    if(alpho <0){
      alpho = 0;
    } else if(alpho >1){
      alpho = 1;
    }
    setState(() {
      appBarApha = alpho;
    });

//    print(appBarApha);



  }
  Future<Null> _handleRefresh()async{
    HomeDao.fetch().then((result){
      setState(() {
        resultString = '请求结果正确';
        resultString = json.encode(result.config);
        print(result.config.searchUrl);
        bannerList = result.bannerList;
        localNavList = result.localNaviList;
        gridNavModel = result.gridNav;
        subNavList = result.subNaviList;
        salesBox = result.salesBox;
        _loading = false;
      });
    }).catchError((e){
      print(e.toString());
      setState(() {
        _loading = false;

      });
    });
    return null;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _handleRefresh();

  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      body:LoadingContainer(Stack(children: [
        MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: RefreshIndicator(onRefresh: _handleRefresh,
              child: NotificationListener(
              onNotification: (scrollNoti){
                if(scrollNoti is ScrollUpdateNotification && scrollNoti.depth==0){
                  _onScroll(scrollNoti.metrics.pixels);
                }
                return false;
              },
              child: _listView,
            ),
            )
        ),

        _appBar
      ],
      ),
        _loading,
      )
    );
  }

  Widget get _listView{
    return ListView(
      children: [
        _bannerView,
        localNavList==[]?Container():Padding(padding: EdgeInsets.fromLTRB(7, 4, 7, 4),child: LocalNav(localNavList),),
        resultString==''?Container():Padding(padding: EdgeInsets.only(left: 6,top: 0,right: 6,bottom: 5),
          child: GridNav(gridNavModel),
        ),
        subNavList==[]?Container():Padding(padding: EdgeInsets.only(left: 6,top: 0,right: 6,bottom: 5),
          child: SubNav(subNavList),
        ),
        resultString==''?Container():Padding(padding: EdgeInsets.only(left: 6,top: 0,right: 6,bottom: 5),
          child: SalesBox(salesBox),
        ),



      ],
    );
  }

  Widget get _appBar{

    return Column(children: [
      Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Color(0x66000000),Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter
          )
        ),
        child: Container(
          padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
          height: 80,
          decoration: BoxDecoration(
              color: Color.fromARGB((appBarApha*255).toInt(), 255, 255, 255)
          ),
          child: SearchBar((){
            print('leftclick');
          },
                (){
            print('eightclick');
          }, (){
            print('speakclick');
            _jumpToSpeakPage();
            },
                (){
            print('inputbox');
            NavigatorUtil.push(context, SearchPage(false, '', '', '请输入搜索内容'));
            },
                (text){print(text);},
            searchBarType: appBarApha>0.2?SearchBarType.homeLight:SearchBarType.home,
          defaultText: SEARCH_BAR_DEFALUT_TEXT,
          ),
        )
      ),
      Container(
        height: appBarApha>0.2?0.5:0,
        decoration: BoxDecoration(boxShadow: [BoxShadow(color: Colors.black12,blurRadius: 0.5)]),
      )
    ],
    );

  }

  Widget get _bannerView{
    return Container(height: 160,
      child: bannerList==[]?Container(): Swiper(itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context,int index){
          return GestureDetector(child: Image.network(bannerList[index].icon,
            fit: BoxFit.fill,
          ),
            onTap: (){
              Navigator.push(context, MaterialPageRoute(builder: (context)=>MyWebView(bannerList[index].url, bannerList[index].statusBarColor, bannerList[index].title, bannerList[index].hideAppBar)));

            },
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }
  _jumpToSpeakPage(){
    Navigator.push(context, MaterialPageRoute(builder: (context)=>SpeakPage()));

  }
}

